package com.linewell.system.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传工具类
 * 
 * @Detail 在controller 中直接调用saveFile方法即可获得文件url
 * @参数 MultipartFile file, HttpServletRequest request, String savepath(需要创建的文件夹)
 * @author 余兆康
 * @Date 2016/10/12
 * 
 */
public class FileUploadUtil {

	private static final Log log = LogFactory.getLog(FileUploadUtil.class);

	/**
	 * 保存文件
	 * 
	 * @return url 返回文件存储在服务器的url地址可将其存入数据库
	 * @author yzk
	 */
	public static String saveFile(MultipartFile file, HttpServletRequest request, String savepath) {

		String url = null;
		if (!file.isEmpty() && savepath != null) {
			try {

				String fileName = createFileName(20);// 获得新随机的文件名
				String fileFormat = file.getOriginalFilename()
						.substring(file.getOriginalFilename().lastIndexOf("."));// 获取文件后缀名
				
				//**********没有图片服务器则使用**************
				 String filePath = request.getSession().getServletContext().getRealPath("/") + savepath + "/"
				 + DateUtils.getYearMonth() + "/";
				
				
				//**********如果有图片服务器则使用,另外在config.properties中添加自定义文件夹fileUplaodPath=/waterorder/upload**************
				//String filePath = savepath + "/" + DateUtils.getYearMonth() + "/";

				File mkdir = new File(filePath);// 如果文件夹不存在则创建文件夹
				if (!mkdir.exists()) {
					mkdir.mkdirs();
				}

				file.transferTo(new File(filePath + fileName + fileFormat));// 转存文件

				log.info(filePath + fileName + fileFormat);
				
				savepath = savepath.substring(savepath.lastIndexOf("/") + 1);
				
				url = getServerUrl(request) + savepath + "/" + DateUtils.getYearMonth() + "/" + fileName + fileFormat;
				log.info(url);

			} catch (Exception e) {
				log.info("上传异常：" + e.getMessage());
				e.printStackTrace();
			}
		}

		return url;
	}

	/**
	 * 检测文件大小
	 * 
	 * @param file
	 *            文件
	 * @param size
	 *            限制大小
	 * @param kb
	 *            如果1M则输入1024，以此类推
	 * @return true 超过限制
	 */
	public static boolean checkFileSize(File file, int kb) {
		long size = file.length();
		if (size > 1024 * kb) {
			return true;
		}
		return false;
	}

	/**
	 * 获得服务器地址
	 * 
	 */
	private static String getServerUrl(HttpServletRequest request) {

		String agent = request.getHeader("user-agent").toLowerCase();
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
				+ "/";
		return basePath;
	}

	/**
	 * 获得随机文件名称
	 * 
	 */
	public static String createFileName(int length) {

		// UUID.randomUUID().toString().replaceAll("-", "")

		String str = "0123456789abcdefghijklmnopqrstuvwxyz";
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < length; i++) {
			builder.append(str.charAt((int) (Math.random() * 36)));
		}

		return builder.toString().toUpperCase();
	}

	/**
	 * 根据提供的名称获得单个resources目录下config.properties属性值 方法一(不能静态0.0.....)
	 * 
	 * @author yzk
	 */
	public String getConfigAttr(String str) {

		String attrStr = null;
		Properties prop = new Properties();
		InputStream is = this.getClass().getResourceAsStream("/config.properties");
		try {
			prop.load(is);
			attrStr = prop.getProperty(str);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return attrStr;

	}

	// @Value("#{configProperties['fileUplaodPath']}")
	// private String fileUplaodPath; // 如果有专门的图片服务器图片存储在该路径
	/**
	 * <bean id="configProperties" class=
	 * "org.springframework.beans.factory.config.PropertiesFactoryBean">
	 * <property name="locations"> <list> <value>classpath:config.properties
	 * </value> </list> </property> </bean>
	 * 
	 */

}
